<template>
  <Select v-model:value="modelValue" class="w-[150px]" placeholder="请选择搜索条件" :options="options" show-search allow-clear :filter-option="filterOption" @focus="handleFocus" @change="handleChange" />
</template>

<script lang="ts" setup>
import { Select } from 'ant-design-vue'
import { ref, watch } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import { listSearchTemplate } from '#/api/common'

interface Props {
  modelValue?: number
}

interface Emits {
  (e: 'update:modelValue', value?: number): void
  (e: 'change', value?: number, content?: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const modelValue = defineModel<number>()
const options = ref<any[]>([])
const searchOption = ref<any[]>([]) // 内部存储选项数据

// 获取搜索条件选项的函数
const fetchSearchTemplateOptions = async (keyword = '') => {
  const res = await listSearchTemplate({
    group_name: 'goodsPurchaseProgress',
    quick_search: keyword,
  })
  const newOptions =
    res.map((item: any) => ({
      label: item.title,
      value: item.id,
      content: item.content,
    })) || []

  options.value = newOptions
  searchOption.value = newOptions
  return newOptions
}

// Select组件获取焦点时触发
const handleFocus = () => {
  // fetchSearchTemplateOptions('')
  handleSearch('')
}

// Select组件搜索时触发（使用防抖）
const handleSearch = useDebounceFn((value: string) => {
  fetchSearchTemplateOptions(value)
}, 300)

// 自定义搜索函数，按label搜索
const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase())
}

// 选择变化时触发
const handleChange = (value: any) => {
  emit('update:modelValue', value)

  if (value) {
    const res = searchOption.value.find((item: any) => item.value === value)
    if (res && res.content) {
      emit('change', value, res.content)
    }
  } else {
    emit('change', undefined, undefined)
  }
}

// 初始化时加载选项
fetchSearchTemplateOptions('')
</script>
